package com.cn.por.auto.db.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.ds.GlobalDSFactory;
import cn.hutool.db.ds.druid.DruidDSFactory;
import cn.hutool.log.level.Level;
import cn.hutool.setting.Setting;
import com.cn.por.auto.datasource.dto.DataSourceConfigADTO;
import com.cn.por.auto.db.DbUtilCustom;
import com.zaxxer.hikari.pool.HikariPool;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DbUtilImpl implements DbUtilCustom {

    @Override
    public <T> List<T> getList(DataSourceConfigADTO dataSourceConfigADTO, String sql, Class<T> beanClass, Object obj) {
        List<T> result = null;
        String dataSourceConfigId = dataSourceConfigADTO.getDataSourceConfigId();
        DataSource ds;
        try {
            ds = DbUtil.getDs(dataSourceConfigId);
        } catch (Exception e) {
            Setting setting = new Setting();
            Map<String, String> stringStringMap = new HashMap<>();
            stringStringMap.put("url", dataSourceConfigADTO.getUrl());
            stringStringMap.put("user", dataSourceConfigADTO.getUsername());
            stringStringMap.put("pass", dataSourceConfigADTO.getPsw());
            stringStringMap.put("driver", dataSourceConfigADTO.getDriver());
            stringStringMap.put("showSql", "true");
            stringStringMap.put("formatSql", "true");
            stringStringMap.put("showParams", "true");
            stringStringMap.put("sqlLevel", "DEBUG");
            stringStringMap.put("initialSize", "5");
            stringStringMap.put("maxActive", "8");
            stringStringMap.put("minIdle", "1");
            stringStringMap.put("maxWait", "0");
            stringStringMap.put("poolPreparedStatements", "false");
            setting.putAll(dataSourceConfigId, stringStringMap);
            DruidDSFactory druidDSFactory = new DruidDSFactory(setting);
            GlobalDSFactory.set(druidDSFactory);
            DbUtil.setShowSqlGlobal(true,true,true, Level.DEBUG);
        }
        try {
            ds = DbUtil.getDs(dataSourceConfigId);

            if(null==obj || (obj instanceof String && StrUtil.isEmpty(obj+""))){
                result = DbUtil.use(ds).query(sql,beanClass);
            }else{
                result = DbUtil.use(ds).query(sql,beanClass,obj);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}

